<template>
  <ContentDetailWrap :title="titleObj[RouteType]" @back="push('/system/announcement')">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      :disabled="RouteType === 2"
      label-width="140px"
    >
      <el-form-item :label="t('announcement.msgCategory_dictText')" prop="msgCategory">
        <el-radio-group v-model="ruleForm.msgCategory">
          <el-radio label="1">{{ t('announcement.Notice') }}</el-radio>
          <el-radio label="2">{{ t('announcement.SystemMessages') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('announcement.title')" prop="title">
        <el-input v-model="ruleForm.title" :placeholder="ruleMsg(t('announcement.title'))" />
      </el-form-item>
      <el-form-item :label="t('announcement.remark')" prop="msgAbstract">
        <el-input
          v-model="ruleForm.msgAbstract"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          :placeholder="ruleMsg(t('announcement.remark'))"
        />
      </el-form-item>
      <el-form-item :label="t('announcement.endTime')" prop="endTime">
        <el-date-picker
          v-model="ruleForm.endTime"
          type="datetime"
          value-format="YYYY-MM-DD hh:mm:ss"
          :placeholder="ruleMsg(t('announcement.endTime'))"
        />
      </el-form-item>
      <el-form-item :label="t('announcement.msgType')">
        <el-radio-group v-model="ruleForm.msgType">
          <el-radio label="USER">{{ t('announcement.specifyUser') }}</el-radio>
          <el-radio label="ALL">{{ t('announcement.allUser') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="ruleForm.msgType === 'USER'">
        <el-form-item :label="t('announcement.specifyUser')" prop="userIds">
          <el-select
            v-model="ruleForm.userIds"
            filterable
            remote
            multiple
            placeholder="请选择指定用户"
            style="width: 400px; margin-right: 10px"
          />
          <el-button type="primary" @click="() => dialogRef?.acceptParams(true)" :icon="Search"
            >选择</el-button
          >
        </el-form-item>
      </template>
      <el-form-item :label="t('announcement.msgCategory_dictText')" prop="priority">
        <el-radio-group v-model="ruleForm.priority">
          <el-radio label="L">{{ t('announcement.low') }}</el-radio>
          <el-radio label="M">{{ t('announcement.middle') }}</el-radio>
          <el-radio label="H">{{ t('announcement.high') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('announcement.msgContent')" prop="msgContent">
        <template v-if="RouteType !== 2">
          <Editor v-model="ruleForm.msgContent" ref="editorRef" />
        </template>
        <div v-else v-html="ruleForm.msgContent"></div>
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">Create</el-button>
        <el-button type="primary" @click="disableForm(ruleFormRef)">Create</el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item> -->
    </el-form>
    <template #right v-if="RouteType !== 2">
      <ElButton type="primary" :loading="loading" @click="save(ruleFormRef)">
        {{ t('exampleDemo.save') }}
      </ElButton>
    </template>
    <Dialog ref="dialogRef" v-model:users="ruleForm.userIds" />
  </ContentDetailWrap>
</template>
<script setup lang="ts">
// import Write from './components/Write.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref, reactive, watch, computed } from 'vue'
import { ElButton } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter, useRoute } from 'vue-router'
import { postAnnountCementAddApi, postAnnountCementEditApi } from '@/api/modules/systemMessage'
import { ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { Search } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
//  @ts-expect-error
import { Editor, EditorExpose } from '@/components/Editor'
// import { IDomEditor } from '@wangeditor/editor'
import Dialog from '@/views/System/announcement/components/dialog.vue'

const { query } = useRoute()

const { push } = useRouter()

const { t } = useI18n()
const titleObj = [t('titObj.add'), t('titObj.edit'), t('titObj.det'), t('titObj.alow')]

// 页面状态判断
const RouteType: any = computed(() => Number(query.type))
const loading = ref(false)
// 新增保存
const save = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const params = cloneDeep(ruleForm.value)
      params.userIds = params.userIds.map((item) => item.id).join(',')
      let res: any
      if (RouteType.value === 1) {
        // 编辑
        res = await postAnnountCementEditApi(params)
      } else {
        // 新增
        res = await postAnnountCementAddApi(params)
      }
      if (res.success) {
        ElMessage.success(res.message)
        push('/system/announcement')
      } else {
        ElMessage.error(res.message)
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// *******************************弹框***************
const dialogRef = ref<InstanceType<typeof Dialog> | null>(null) // 弹框

// *******************************校验规则***************
const ruleFormRef = ref<FormInstance>()
const ruleMsg = (text) => t('announcement.place') + text
const ruleForm = ref<{ [key: string]: any }>({
  id: '',
  msgCategory: '1',
  userIds: [],
  title: '',
  msgAbstract: '',
  endTime: '', // 结束日期
  msgType: 'ALL', // 接收用户 - 默认全部
  msgContent: '', // 内容
  priority: 'H' // 消息类型 - 默认 H
})
// form 赋值
if (query.row && RouteType.value) {
  const data = JSON.parse(query.row as any)
  Object.keys(ruleForm.value).forEach((key) => {
    ruleForm.value[key] = data[key]
  })
  ruleForm.value.userIds = JSON.parse(query.row as any).userIds.split(',')
}
const rules = reactive<FormRules>({
  msgCategory: [
    { required: true, message: ruleMsg(t('announcement.msgCategory_dictText')), trigger: 'change' }
  ],
  title: [
    { required: true, message: ruleMsg(t('announcement.title')), trigger: 'blur' },
    { max: 100, message: '长度不能超过100', trigger: 'blur' }
  ],
  msgAbstract: [
    { required: true, message: ruleMsg(t('announcement.remark')), trigger: 'blur' },
    { max: 1000, message: '长度不能超过1000', trigger: 'blur' }
  ],
  endTime: [
    { required: true, type: 'date', message: ruleMsg(t('announcement.endTime')), trigger: 'change' }
  ],
  userIds: [
    {
      type: 'array',
      required: false,
      message: ruleMsg(t('announcement.specifyUser')),
      trigger: 'change'
    }
  ],
  msgContent: [
    { required: false, message: ruleMsg(t('announcement.msgContent')), trigger: 'blur' },
    { max: 30000, message: '长度不能超过30000', trigger: 'blur' }
  ]
})
// 监听type 修改校验规则
watch(
  () => ruleForm.value.msgType,
  (val) => {
    // @ts-expect-error
    rules.userIds[0].required = Boolean(val == 'USER')
  }
)
// 富文本 编辑
// const editorRef = ref<typeof Editor & EditorExpose>()
// // const defaultHtml = ref('')
// const change = (editor: IDomEditor) => {
//   console.log(editor.getHtml())
// }
// const submitForm = (res) => {
//   console.log(res)
// }
// const resetForm = (res) => {
//   console.log(res)
// }
</script>
